package com.servicelive.service;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;

import org.hibernate.Session;

import com.h2m.service.OrderManageService;
import com.servicelive.ServiceLiveCommonService.OrderedItemDetails;
import com.servicelivedb.ServiceliveDB;
import com.servicelivedb.data.Customer;
import com.servicelivedb.data.Items;
import com.servicelivedb.data.Order;
import com.servicelivedb.data.OrderItems;
import com.wavemaker.runtime.RuntimeAccess;
import com.wavemaker.runtime.javaservice.JavaServiceSuperClass;
import com.wavemaker.runtime.service.annotations.ExposeToClient;

/**
 * This is a client-facing service class. All public methods will be exposed to
 * the client. Their return values and parameters will be passed to the client
 * or taken from the client, respectively. This will be a singleton instance,
 * shared between all requests.
 * 
 * To log, call the superclass method log(LOG_LEVEL, String) or log(LOG_LEVEL,
 * String, Exception). LOG_LEVEL is one of FATAL, ERROR, WARN, INFO and DEBUG to
 * modify your log level. For info on these levels, look for tomcat/log4j
 * documentation
 */
@ExposeToClient
public class OrderService extends JavaServiceSuperClass {
	/*
	 * Pass in one of FATAL, ERROR, WARN, INFO and DEBUG to modify your log
	 * level; recommend changing this to FATAL or ERROR before deploying. For
	 * info on these levels, look for tomcat/log4j documentation
	 */
	public OrderService() {
		super(INFO);
	}

	public String placeOrder(OrderDetails order, Integer vendorId) {

		String result = "";
		ServiceliveDB db = (ServiceliveDB) RuntimeAccess.getInstance()
				.getServiceBean("serviceliveDB");
		MailSenderService mailsend = (MailSenderService) RuntimeAccess
				.getInstance().getServiceBean("MailSenderService");

		try {
			System.out.println("vendorId=" + vendorId);
			System.out.println("Items=" + order.getDetails());
			System.out.println("customerId=" + order.getCustomerId());

			db.begin();

			Session session = db.getDataServiceManager().getSession();

			Customer vendor = (Customer) session.get(Customer.class, vendorId);
			Customer customer = (Customer) session.get(Customer.class,
					order.getCustomerId());

			String blockName = customer.getBlock().getBlockName();
			System.out.println("blockName" + blockName);
			String doorName = customer.getDoor().getDoorName();
			System.out.println("doorName" + doorName);
			String address = customer.getProject().getProjectName() + " "
					+ blockName + " " + doorName;
			Order customerOrder = new Order();
			customerOrder.setProject(customer.getProject());
			customerOrder.setCustomerByCustomerId(customer);
			customerOrder.setCustomerByVendorId(vendor);
			Calendar startingCalendar = Calendar.getInstance(TimeZone.getTimeZone("Asia/Calcutta"));
			
			customerOrder.setOrderDt(startingCalendar.getTime());
			customerOrder.setUpdatedBy(customer.getEmail());
			customerOrder.setAddress(address);
			customerOrder.setStatus("NEW");
			customerOrder.setActive(true);
			customerOrder.setComments(order.getComment());
			customerOrder.setContactNum(customer.getPrimaryPhone());
			session.save(customerOrder);
			Float price = 0f;
			String orderDetails = "";
			for (OrderedItemDetails od : order.getDetails()) {
				if (od.getQuantity() != null && od.getQuantity().intValue() > 0) {

					OrderItems orderItem = new OrderItems();
					Items item = (Items) session.get(Items.class,
							od.getItemId());

					orderItem.setOrder(customerOrder);
					orderItem.setQuantity(od.getQuantity());
					float itemTotalPrice = od.getOrderedPrice()
							* od.getQuantity().floatValue();
					orderItem.setPrice(new BigDecimal(itemTotalPrice));
					orderItem.setStatus("NEW");
					orderItem.setItems(item);
					customerOrder.getOrderItemses().add(orderItem);
					session.save(orderItem);

					orderDetails = orderDetails + " " + item.getItemName()
							+ " - " + od.getQuantity();

					price += itemTotalPrice;
				}
			}
			customerOrder.setTotalPrice(new BigDecimal(price));
			session.saveOrUpdate(customerOrder);

			db.commit();
			log(INFO, "Order created successfully: Order number is:"
					+ customerOrder.getOrderId() + ";Customer Id,email="
					+ customer.getCustomerId() + "&" + customer.getEmail()
					+ ";VendorName=" + vendor.getName());

			result = "Your Last Order# "
					+ customerOrder.getOrderId()
					+ " and Total Price is "
					+ customerOrder.getTotalPrice().floatValue()
					+ " Rs.</br>"
					+ (vendor.getVendor_msg() == null ? "" : vendor
							.getVendor_msg());
			orderDetails = orderDetails + " and Total Price is "
					+ customerOrder.getTotalPrice().floatValue() + " Rs.";
			// SMSService smsService = new SMSService();
			OrderManageService smsService = (OrderManageService) RuntimeAccess
					.getInstance().getServiceBean("OrderManageService");

			String sMessage = smsService.ConstructTemplate(vendor.getName(),
					customer.getName(), customer.getAddress(),
					customer.getPrimaryPhone(),
					customerOrder.getOrderId() + "", blockName, doorName,
					orderDetails);

			String response = smsService.SMSSender(
					"91" + vendor.getPrimaryPhone(), sMessage);
			System.out.println(response);

			log(INFO, "sending vendor email" + customerOrder.getOrderId()
					+ ";Customer Id,email=" + customer.getCustomerId() + "&"
					+ customer.getEmail() + ";VendorName=" + vendor.getName());

			mailsend.sendEmailToVendor(String.valueOf(customerOrder
					.getOrderId()));

		} catch (Exception e) {
			db.rollback();
			System.out.println(e.getMessage());
			result = "Error during order creation,Please try again";
			log(ERROR, "Error during placing oreder:", e);
		}

		return result;
	}

	public void updateMasterOrderStatus(Integer orderId, String orderComment) {

		ServiceliveDB db = (ServiceliveDB) RuntimeAccess.getInstance()
				.getServiceBean("serviceliveDB");

		try {

			db.begin();

			Session session = db.getDataServiceManager().getSession();

			Order order = (Order) session.get(Order.class, orderId);

			order.setVendor_comment(orderComment);
			
			for (OrderItems item : order.getOrderItemses()) {

				item.setStatus("Delivered");
				session.update(item);

			}
			order.setStatus("Delivered");

			session.update(order);

			db.commit();

		} catch (Exception e) {
			db.rollback();
			System.out.println(e.getMessage());

			log(ERROR, "Error during updating order status", e);
		}
	}

	@SuppressWarnings("unused")
	public void updatePartialOrderStatus(Integer orderId, String orderComment,
			String itemIds) {

		ServiceliveDB db = (ServiceliveDB) RuntimeAccess.getInstance()
				.getServiceBean("serviceliveDB");

		try {
			System.out.println("$$$$$$$$$$$$$$$$  +" + orderId
					+ ";orderComment=" + orderComment + ";itemIds==" + itemIds);

			db.begin();

			Session session = db.getDataServiceManager().getSession();

			Order order = (Order) session.get(Order.class, orderId);
			boolean noneDelivered = false;
			boolean allItemDelivered = true;

			String[] itemIdDelivered = null;
			List<String> itemIdList = null;

			if (itemIds != null || itemIds != "") {
				itemIdDelivered = itemIds.split(",");
				itemIdList = Arrays.asList(itemIdDelivered);

			} else {
				noneDelivered = true;
			}

			//order.setComments(order.getComments() == null ? "" : order.getComments());
			
			order.setVendor_comment(orderComment == null ? "" : orderComment);
			
			if (itemIdList != null && itemIdList.size() > 0) {
				for (OrderItems item : order.getOrderItemses()) {

					if (itemIdList.contains(String.valueOf(item
							.getOrderItemId()))) {

						item.setStatus("Delivered");

						System.out.println("$$$$$$$$$$$$$$$$  +"
								+ String.valueOf(item.getOrderItemId())
								+ ";Delivered=");

					} else {
						item.setStatus("NEW");

					}
					session.update(item);

					if (!item.getStatus().equalsIgnoreCase("Delivered")) {
						allItemDelivered = false;

					}

				}
				if (allItemDelivered) {
					order.setStatus("Delivered");

				} else {

					order.setStatus("Partly Delivered");
				}
			} else {

				if (noneDelivered) {

					order.setStatus("NEW");
				}
			}

			session.update(order);

			db.commit();

		} catch (Exception e) {
			db.rollback();
			System.out.println(e.getMessage());

			log(ERROR, "Error during updating order status", e);
		}
	}

	public void updateVendorOrderStatus(Integer vendorId) {

		ServiceliveDB db = (ServiceliveDB) RuntimeAccess.getInstance()
				.getServiceBean("serviceliveDB");

		try {

			db.begin();

			Session session = db.getDataServiceManager().getSession();

			Order order = (Order) session.get(Order.class, vendorId);
			boolean anyItemDelivered = false;
			boolean allItemDelivered = true;
			for (OrderItems item : order.getOrderItemses()) {

				if (item.getStatus().equalsIgnoreCase("Delivered")) {
					anyItemDelivered = true;
				} else {
					allItemDelivered = false;
				}

			}
			System.out.println("Order status :::" + allItemDelivered);
			System.out.println("Order status anyItemDelivered:::"
					+ anyItemDelivered);
			if (allItemDelivered) {
				order.setStatus("Delivered");

			} else if (anyItemDelivered) {

				order.setStatus("Partly Delivered");
			}

			else if (!allItemDelivered && !anyItemDelivered) {
				order.setStatus("NEW");
			}

			session.update(order);

			db.commit();

		} catch (Exception e) {
			db.rollback();
			System.out.println(e.getMessage());

			log(ERROR, "Error during updating order status", e);
		}
	}
	public void updateOrderStatus(Integer orderId, String status,String vendorComment) {

		ServiceliveDB db = (ServiceliveDB) RuntimeAccess.getInstance()
				.getServiceBean("serviceliveDB");
		System.out.println("orderId=" + orderId);
		System.out.println("status=" + status);
		try {

			db.begin();

			Session session = db.getDataServiceManager().getSession();

			Order order = (Order) session.load(Order.class,
					orderId);

			order.setStatus(status);
			order.setVendor_comment(vendorComment);
			session.update(order);

			db.commit();

		} catch (Exception e) {
			db.rollback();
			System.out.println(e.getMessage());

			log(ERROR, "Error during updating order  status", e);
		}
	}
	public void updateOrderItemStatus(Integer orderItemId, String status) {

		ServiceliveDB db = (ServiceliveDB) RuntimeAccess.getInstance()
				.getServiceBean("serviceliveDB");
		System.out.println("orderItemId=" + orderItemId);
		System.out.println("status=" + status);
		try {

			db.begin();

			Session session = db.getDataServiceManager().getSession();

			OrderItems order = (OrderItems) session.load(OrderItems.class,
					orderItemId);

			order.setStatus(status);

			session.update(order);

			db.commit();

		} catch (Exception e) {
			db.rollback();
			System.out.println(e.getMessage());

			log(ERROR, "Error during updating order item status", e);
		}
	}

	public static class OrderDetails {

		private Integer customerId;
		private String comment;

		private List<OrderedItemDetails> details;

		private Integer vendorId;

		public Integer getCustomerId() {
			return customerId;
		}

		public String getComment() {
			return comment;
		}

		public void setComment(String comment) {
			this.comment = comment;
		}

		public void setCustomerId(Integer customerId) {
			this.customerId = customerId;
		}

		public Integer getVendorId() {
			return vendorId;
		}

		public void setVendorId(Integer vendorId) {
			this.vendorId = vendorId;
		}

		public List<OrderedItemDetails> getDetails() {
			return details;
		}

		public void setDetails(List<OrderedItemDetails> details) {
			this.details = details;
		}

	}

}
